import multiprocessing
import threading

import news_load
import convert_to_html
import os
import scheduler
from news_analysis_app import create_flask_app
from news_load import newsLoadInstance

def start_tasks():
    scheduler.start_scheduler()

def start_flask():
    print("启动 Flask 应用...")
    app = create_flask_app()
    app.run(host='0.0.0.0', port=8080)


# 程序的入口
if __name__ == "__main__":
    # 生成新闻
    # assistant = news_load.NewsLoad()
    # filename = assistant.run()
    filename = newsLoadInstance.run()   # 采用单例模式
    # 将生成的 Markdown 文件转换为 HTML 并在浏览器中打开
    html_file = convert_to_html.convert_md_to_html(filename)
    convert_to_html.open_in_browser(html_file)
    
    # 如果用户配置了邮件发送功能，则发送邮件
    try:
        # 生成适合邮件的 HTML 版本
        email_html_file = convert_to_html.convert_md_to_html_for_email(filename)
        
        # 读取 HTML 内容
        with open(email_html_file, 'r', encoding='utf-8') as f:
            html_content = f.read()
        
        # 尝试导入邮件配置并发送
        if os.path.exists('email_config.json'):
            from emailTool import send_email
            
            # 发送邮件
            send_email(html_content)
        else:
            print("未找到邮件配置文件 email_config.json，跳过邮件发送")
    except Exception as e:
        print(f"邮件发送过程出错: {e}")

    # 定时任务与flask应用多线程隔离

    # 启动flask应用，使用多线程
    flask_thread = threading.Thread(target=start_flask)
    flask_thread.daemon = True  # 设置为守护线程，使其随主进程退出而退出
    flask_thread.start()

    # 开启定时任务
    # scheduler.start_scheduler()
    start_tasks()
    # scheduler_thread = threading.Thread(target=start_tasks)
    # scheduler_thread.daemon = True
    # scheduler_thread.start()


